/*
   Copyright (c) 2020, zoomdy
   MicroAmpereII is licensed under Mulan PSL v2.
   You can use this software according to the terms and conditions of the Mulan PSL v2.
   You may obtain a copy of Mulan PSL v2 at:
            http://license.coscl.org.cn/MulanPSL2
   THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
   EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
   MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
   See the Mulan PSL v2 for more details.
 */

#include "gd32vf103.h"
#include "hal_led.h"

#define LED_R_PORT               GPIOC
#define LED_R_PIN                GPIO_PIN_13

#define LED_G_PORT               GPIOA
#define LED_G_PIN                GPIO_PIN_1

#define LED_B_PORT               GPIOA
#define LED_B_PIN                GPIO_PIN_2

typedef struct
{
    uint32_t port;
    uint32_t pin;
}hal_led_gpio_t;

static hal_led_gpio_t hal_led_gpio[3] = {
        { LED_R_PORT, LED_R_PIN },
        { LED_G_PORT, LED_G_PIN },
        { LED_B_PORT, LED_B_PIN },
};


void hal_led_init_(void)
{
    int i;

    rcu_periph_clock_enable(RCU_GPIOA);
    rcu_periph_clock_enable(RCU_GPIOC);

    for(i = 0; i < 3; i++) {
        gpio_init(hal_led_gpio[i].port, GPIO_MODE_OUT_PP, GPIO_OSPEED_2MHZ, hal_led_gpio[i].pin);
        gpio_bit_set(hal_led_gpio[i].port, hal_led_gpio[i].pin);
    }
}


void hal_led_on(hal_led_t led)
{
    gpio_bit_reset(hal_led_gpio[led].port, hal_led_gpio[led].pin);
}


void hal_led_off(hal_led_t led)
{
    gpio_bit_set(hal_led_gpio[led].port, hal_led_gpio[led].pin);
}


void hal_led_toggle(hal_led_t led)
{
    if(gpio_input_bit_get(hal_led_gpio[led].port, hal_led_gpio[led].pin)) {
        gpio_bit_reset(hal_led_gpio[led].port, hal_led_gpio[led].pin);
    } else {
        gpio_bit_set(hal_led_gpio[led].port, hal_led_gpio[led].pin);
    }
}
